package cn.lili.controller.wallet;

import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.order.order.entity.enums.PayStatusEnum;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.permission.entity.dos.AdminUser;
import cn.lili.modules.permission.service.AdminUserService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawApply;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawItem;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.entity.dos.WalletDetail;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.enums.WithdrawStatusEnum;
import cn.lili.modules.wallet.entity.vo.MemberWalletVO;
import cn.lili.modules.wallet.entity.vo.WalletDetailVO;
import cn.lili.modules.wallet.entity.vo.WalletFrozenDetailVO;
import cn.lili.modules.wallet.service.*;
import cn.lili.modules.whitebar.service.CommissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 管理端,预存款接口
 *
 * @author pikachu
 * @since 2020/11/16 10:07 下午
 */
@RestController
@Api(tags = "管理端,预存款接口")
@RequestMapping("/manager/members/wallet")
public class MemberWalletManagerController {
	@Autowired
	private MemberWalletService memberWalletService;
	@Autowired
	private CommissionService commissionService;

	@Autowired
	private WalletLogDetailService walletLogDetailService;

	@Autowired
	private WalletDetailService walletDetailService;

	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private PartnerService partnerService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private TransferService transferService;

	@Autowired
	private MemberWithdrawApplyService memberWithdrawApplyService;

	@Autowired
	private RechargeService rechargeService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private WalletFrozenDetailService walletFrozenDetailService;

	@GetMapping
	@ApiOperation(value = "查询会员预存款余额")
	@ApiImplicitParams({@ApiImplicitParam(name = "memberId", value = "会员ID", paramType = "query"),
			@ApiImplicitParam(name = "owner", value = "会员来源", paramType = "query")})
	public ResultMessage<MemberWalletVO> get(@RequestParam("memberId") String memberId,
			@RequestParam("owner") String owner) {
		return ResultUtil.data(memberWalletService.getMemberWallet(memberId, owner));
	}

	@RequestMapping(value = "/walletAll")
	@ApiOperation(value = "平台钱包收入汇总")
	public ResultMessage<Map<String, Object>> walletAll() {
		Map<String, Object> map = new HashMap<>();
		String memberId = "admin";
		// 推广-会员
		MemberWalletVO promoteHy = null;
		promoteHy = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_HY.name());
		Double promoteHyMoney = promoteHy != null
				? BigDecimal.valueOf(promoteHy.getMemberWallet()).setScale(2, RoundingMode.DOWN).doubleValue()
				: 0D;
		map.put("promoteHyMoney", promoteHyMoney);
		// 推广-服务
		MemberWalletVO promoteFw = null;
		promoteFw = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_FW.name());
		Double promoteFwMoney = promoteFw != null
				? BigDecimal.valueOf(promoteFw.getMemberWallet()).setScale(2, RoundingMode.DOWN).doubleValue()
				: 0D;
		map.put("promoteFwMoney", promoteFwMoney);
		// 充值钱包
		MemberWallet recharge = memberWalletService.getMemberWalletInfo(memberId, WalletOwnerEnum.RECHARGE.name());
		Double rechargeMoney = BigDecimal.valueOf(recharge.getMemberWallet()).setScale(2, RoundingMode.DOWN)
				.doubleValue();
		map.put("rechargeMoney", rechargeMoney);
		// 冻结资金
//		MemberWallet sale = memberWalletService.getMemberWalletInfo(memberId, WalletOwnerEnum.SALE.name());
//		Double saleMoney = BigDecimal.valueOf(sale.getMemberWallet()).setScale(2, RoundingMode.DOWN).doubleValue();
//		Map<String, Object> maps = orderService.findFrozenMap();
//		map.put("saleMoney", maps != null ? maps.get("commission") : 0D);
		QueryWrapper queryWrappers = new QueryWrapper();
		PageVO page = new PageVO();
		page.setPageSize(999999999);
		page.setPageNumber(1);
		queryWrappers.groupBy("a.sn");
		IPage<WalletFrozenDetailVO> data = walletFrozenDetailService.getWalletFrozenDetail(queryWrappers, page);
		List<WalletFrozenDetailVO> walletFrozenDetailVOList = data.getRecords();
		Double commission = 0D;
		for (WalletFrozenDetailVO s : walletFrozenDetailVOList) {
			commission = CurrencyUtil.add(s.getCommission(), commission);
		}
		map.put("saleMoney", commission);
		// 回收
		Double memberApplyMoney = 0D;
		QueryWrapper<MemberWithdrawApply> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("apply_status", WithdrawStatusEnum.FINISH.name(), WithdrawStatusEnum.INPAYMENT.name(),
				WithdrawStatusEnum.VIA_AUDITING.name());
		queryWrapper.ne("member_id", memberId);
		queryWrapper.eq("delete_flag", 0);
		List<MemberWithdrawApply> memberWithdrawApplyList = memberWithdrawApplyService.list(queryWrapper);
		if (CollectionUtils.isNotEmpty(memberWithdrawApplyList)) {
			for (MemberWithdrawApply apply : memberWithdrawApplyList) {
				memberApplyMoney = CurrencyUtil.add(memberApplyMoney,
						apply.getApplyPrice() != null ? apply.getApplyPrice() : 0D);
			}
		}
		map.put("memberApplyMoney", BigDecimal.valueOf(memberApplyMoney).setScale(2, RoundingMode.DOWN).doubleValue());
		// 提现
		Double adminApplyMoney = 0D;
		QueryWrapper<MemberWithdrawApply> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.eq("apply_status", WithdrawStatusEnum.FINISH.name());
		queryWrapper1.eq("member_id", memberId);
		queryWrapper1.eq("delete_flag", 0);
		List<MemberWithdrawApply> memberWithdrawApplyList1 = memberWithdrawApplyService.list(queryWrapper1);
		if (CollectionUtils.isNotEmpty(memberWithdrawApplyList1)) {
			for (MemberWithdrawApply apply : memberWithdrawApplyList1) {
				adminApplyMoney = CurrencyUtil.add(adminApplyMoney,
						apply.getApplyPrice() != null ? apply.getApplyPrice() : 0D);
			}
		}
		map.put("adminApplyMoney", BigDecimal.valueOf(adminApplyMoney).setScale(2, RoundingMode.DOWN).doubleValue());
		// 转账
		Double transferMoney = 0D;
		QueryWrapper<Transfer> queryWrapper2 = new QueryWrapper<>();
		queryWrapper2.eq("state", "success");
		queryWrapper2.eq("payer", memberId);
		queryWrapper2.eq("delete_flag", 0);
		List<Transfer> list = transferService.list(queryWrapper2);
		if (CollectionUtils.isNotEmpty(list)) {
			for (Transfer transfer : list) {
				transferMoney = CurrencyUtil.add(transferMoney,
						transfer.getTransferMoney() != null ? transfer.getTransferMoney() : 0D);
			}
		}
		map.put("transferMoney", BigDecimal.valueOf(transferMoney).setScale(2, RoundingMode.DOWN).doubleValue());
		return ResultUtil.data(map);
	}

	@RequestMapping(value = "/all")
	@ApiOperation(value = "平台钱包收入汇总")
	public ResultMessage<Map<String, Object>> all() {
		Map<String, Object> map = new HashMap<>();
		AuthUser currentUser = UserContext.getCurrentUser();
		String memberId = "admin";
		MemberWalletVO promoteHy = null;
		MemberWalletVO promoteFw = null;
		// MemberWalletVO promote = null;
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			AdminUser adminUser = adminUserService.getById(currentUser.getId());
			if (null != adminUser) {
				QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("mobile", adminUser.getMobile());
				Member member = memberService.getOne(queryWrapper);
				if (null != member) {
					QueryWrapper<Partner> wrapper = new QueryWrapper<>();
					wrapper.eq("member_id", member.getId());
					wrapper.eq("partner_type", "4");// 代理商
					wrapper.eq("delete_flag", 0);
					wrapper.eq("audit_state", "PASS");
					Partner one = partnerService.getOne(wrapper);
					if (null != one) {
						memberId = member.getId();
						promoteHy = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_HY.name());
						promoteFw = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_FW.name());
					} else {
						// promote = memberWalletService.getMemberWallet(memberId,
						// WalletOwnerEnum.PROMOTE.name());
						promoteHy = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_HY.name());
						promoteFw = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_FW.name());
					}
				} else {
					// promote = memberWalletService.getMemberWallet(memberId,
					// WalletOwnerEnum.PROMOTE.name());
					promoteHy = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_HY.name());
					promoteFw = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_FW.name());
				}
			} else {
				// promote = memberWalletService.getMemberWallet(memberId,
				// WalletOwnerEnum.PROMOTE.name());
				promoteHy = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_HY.name());
				promoteFw = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_FW.name());
			}
		} else {
			// promote = memberWalletService.getMemberWallet(memberId,
			// WalletOwnerEnum.PROMOTE.name());
			promoteHy = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_HY.name());
			promoteFw = memberWalletService.getMemberWallet(memberId, WalletOwnerEnum.PROMOTE_FW.name());
		}
		MemberWallet recharge = memberWalletService.getMemberWalletInfo(memberId, WalletOwnerEnum.RECHARGE.name());
		MemberWallet sale = memberWalletService.getMemberWalletInfo(memberId, WalletOwnerEnum.SALE.name());
		Double rechargeMoney = recharge.getMemberWallet();
		Double saleMoney = sale.getMemberWallet();
		// Double promoteMoney = promote != null ? promote.getMemberWallet() : 0D;
		Double promoteHyMoney = promoteHy != null ? promoteHy.getMemberWallet() : 0D;
		Double promoteFwMoney = promoteFw != null ? promoteFw.getMemberWallet() : 0D;
		map.put("rechargeMoney", Math.floor(rechargeMoney * 100) / 100);
		// map.put("promoteMoney",promoteMoney);
		map.put("saleMoney", Math.floor(saleMoney * 100) / 100);
		map.put("promoteHyMoney", Math.floor(promoteHyMoney * 100) / 100);
		map.put("promoteFwMoney", Math.floor(promoteFwMoney * 100) / 100);
		// map.put("allMoney",CurrencyUtil.add(saleMoney,rechargeMoney,promoteMoney,promoteHyMoney,promoteFwMoney));
		map.put("allMoney",
				Math.floor(CurrencyUtil.add(saleMoney, rechargeMoney, promoteHyMoney, promoteFwMoney) * 100) / 100);
		return ResultUtil.data(map);
	}

	@RequestMapping(value = "/outlay")
	@ApiOperation(value = "平台钱包支出明细")
	public ResultMessage<IPage<WalletDetailVO>> outlay(PageVO pageVO, WalletDetailVO walletDetailVO) {
		QueryWrapper<WalletDetailVO> queryWrapper = new QueryWrapper<>();
		AuthUser currentUser = UserContext.getCurrentUser();
		String memberId = "admin";
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			AdminUser adminUser = adminUserService.getById(currentUser.getId());
			if (null != adminUser) {
				QueryWrapper<Member> queryWrapper1 = new QueryWrapper<>();
				queryWrapper1.eq("mobile", adminUser.getMobile());
				Member member = memberService.getOne(queryWrapper1);
				if (null != member) {
					QueryWrapper<Partner> wrapper = new QueryWrapper<>();
					wrapper.eq("member_id", member.getId());
					wrapper.eq("partner_type", "4");// 代理商
					wrapper.eq("delete_flag", 0);
					wrapper.eq("audit_state", "PASS");
					Partner one = partnerService.getOne(wrapper);
					if (null != one) {
						memberId = member.getId();
					}
				}
			}
		}
		queryWrapper.eq("d.payer", memberId);
		if (StringUtils.isNotEmpty(walletDetailVO.getSn())) {
			queryWrapper.eq("d.sn", walletDetailVO.getSn());
		}
		if (StringUtils.isNotEmpty(walletDetailVO.getTransactionType())) {
			queryWrapper.eq("d.transaction_type", walletDetailVO.getTransactionType());
		}
		if (StringUtils.isNotEmpty(walletDetailVO.getMobile())) {
			queryWrapper.like("m.mobile", walletDetailVO.getMobile());
		}
		if (StringUtils.isNotEmpty(walletDetailVO.getStartTime())) {
			queryWrapper.ge("d.create_time", walletDetailVO.getStartTime());
			queryWrapper.le("d.create_time", walletDetailVO.getEndTime());
		} else {
			// 获取当前月份
			Calendar cal = Calendar.getInstance();
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH) + 1;
			String m = year + "-" + (month < 10 ? "0" + month : month);
			queryWrapper.eq("DATE_FORMAT(d.create_time,'%Y-%m')", m);
		}
		IPage<WalletDetailVO> list = walletDetailService.getOutlayList(pageVO, queryWrapper);
		return ResultUtil.data(list);
	}

	@RequestMapping(value = "/income")
	@ApiOperation(value = "平台钱包收入明细")
	public ResultMessage<IPage<WalletDetailVO>> income(PageVO pageVO, WalletDetailVO walletDetailVO) {
		QueryWrapper<WalletDetailVO> queryWrapper = new QueryWrapper<>();
		AuthUser currentUser = UserContext.getCurrentUser();
		String memberId = "admin";
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			AdminUser adminUser = adminUserService.getById(currentUser.getId());
			if (null != adminUser) {
				QueryWrapper<Member> queryWrapper1 = new QueryWrapper<>();
				queryWrapper1.eq("mobile", adminUser.getMobile());
				Member member = memberService.getOne(queryWrapper1);
				if (null != member) {
					QueryWrapper<Partner> wrapper = new QueryWrapper<>();
					wrapper.eq("member_id", member.getId());
					wrapper.eq("partner_type", "4");// 代理商
					wrapper.eq("delete_flag", 0);
					wrapper.eq("audit_state", "PASS");
					Partner one = partnerService.getOne(wrapper);
					if (null != one) {
						memberId = member.getId();
					}
				}
			}
		}
		queryWrapper.eq("d.payee", memberId);
		if (StringUtils.isNotEmpty(walletDetailVO.getSn())) {
			queryWrapper.eq("d.sn", walletDetailVO.getSn());
		}
		if (StringUtils.isNotEmpty(walletDetailVO.getTransactionType())) {
			queryWrapper.eq("d.transaction_type", walletDetailVO.getTransactionType());
		}
		if (StringUtils.isNotEmpty(walletDetailVO.getMobile())) {
			queryWrapper.like("m.mobile", walletDetailVO.getMobile());
		}
		if (StringUtils.isNotEmpty(walletDetailVO.getStartTime())) {
			queryWrapper.ge("d.create_time", walletDetailVO.getStartTime());
			queryWrapper.le("d.create_time", walletDetailVO.getEndTime());
		} else {
			// 获取当前月份
			Calendar cal = Calendar.getInstance();
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH) + 1;
			String m = year + "-" + (month < 10 ? "0" + month : month);
			queryWrapper.eq("DATE_FORMAT(d.create_time,'%Y-%m')", m);
		}
		IPage<WalletDetailVO> list = walletDetailService.getIncomeList(pageVO, queryWrapper);
		return ResultUtil.data(list);
	}

	@ApiOperation(value = "PC查看销售提现订单明细")
	@RequestMapping("/querySellAll")
	public ResultMessage<IPage<MemberWithdrawItem>> querySellAll(PageVO page, MemberWithdrawApply memberWithdrawApply,
			String owner) {
		QueryWrapper<MemberWithdrawApply> queryWrappers = new QueryWrapper<>();
		queryWrappers.eq("delete_flag", "0");
		// queryWrapper.eq(CharSequenceUtil.isNotEmpty(owner),"owner",owner);
		queryWrappers.eq(CharSequenceUtil.isNotEmpty(memberWithdrawApply.getSn()), "sn", memberWithdrawApply.getSn());
		queryWrappers.apply(" DATE_FORMAT( create_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )");
		queryWrappers.orderByDesc("create_time");
		QueryWrapper<MemberWithdrawItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("delete_flag", "0");
		// queryWrapper.eq(CharSequenceUtil.isNotEmpty(owner),"owner",owner);
		queryWrapper.eq(CharSequenceUtil.isNotEmpty(memberWithdrawApply.getSn()), "sn", memberWithdrawApply.getSn());
		queryWrapper.apply(" DATE_FORMAT( create_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )");
		queryWrapper.orderByDesc("create_time");
		IPage<MemberWithdrawApply> memberWithdrawApplyIPages = memberWithdrawApplyService.queryWithdrawApplyList(page,
				queryWrappers);
		IPage<MemberWithdrawItem> memberWithdrawApplyIPage = memberWithdrawApplyService.queryItemLists(page,
				queryWrapper);
		for (MemberWithdrawApply a : memberWithdrawApplyIPages.getRecords()) {
			for (MemberWithdrawItem s : memberWithdrawApplyIPage.getRecords()) {
				// s.setInspectTime(a.getInspectTime());
				// s.setApplyStatus(a.getApplyStatus());
				double div = CurrencyUtil.div(s.getRealMoney(), s.getApplyMoney(), 5);
				Double sub = CurrencyUtil.sub(s.getApplyMoney(), s.getRealMoney());
				s.setFee(div);
				// s.setHandlingMoney(sub);
			}
		}
		return ResultUtil.data(memberWithdrawApplyIPage);
	}

	@RequestMapping(value = "/recharge")
	@ApiOperation(value = "平台钱包充值")
	public ResultMessage<Recharge> recharge(@RequestParam("price") Double price) {
		// 创建充值记录，平台充值默认已支付
		String sn = "Y" + SnowFlake.getId();
		Recharge recharge = new Recharge(sn, "admin", "平台", price, "4", price, WalletOwnerEnum.RECHARGE.name(), 0D,
				null);
		recharge.setPayStatus(PayStatusEnum.PAID.name());
		recharge.setPayTime(new Date());
		rechargeService.save(recharge);
		// 钱包加钱
		MemberWallet admin = memberWalletService.getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台");

		// 修改钱包余额
		WalletDetail detail = new WalletDetail();
		detail.setSn(sn);
		detail.setTransactionType(DepositServiceTypeEnum.WALLET_RECHARGE.name());
		detail.setPayee(admin.getMemberId());
		detail.setPayeeName(admin.getMemberName());
		detail.setPayeeOwner(admin.getOwner());
		detail.setPayeeBeforeMoney(admin.getMemberWallet());
		detail.setMoney(price);

		admin.setMemberWallet(CurrencyUtil.add(admin.getMemberWallet(), price));
		memberWalletService.update(admin,
				new QueryWrapper<MemberWallet>().eq("id", admin.getId()).eq("owner", admin.getOwner()));
		detail.setPayeeAfterMoney(admin.getMemberWallet());

		walletDetailService.save(detail);
		return ResultUtil.data(recharge);
	}

	@ApiOperation(value = "根据手机号查询会员信息")
	@ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", paramType = "path")
	@RequestMapping("/{mobile}")
	public ResultMessage<MemberVO> getUserInfo(@PathVariable String mobile) {
		QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mobile", mobile);
		queryWrapper.orderByAsc("c.LEVEL");
		queryWrapper.last("limit 1");
		MemberVO memberVO = memberService.findByPhone(queryWrapper);
		return ResultUtil.data(memberVO);
	}

}
